import { defineStore } from 'pinia'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

export interface TagsViewState {
  visitedViews: any[]
  cachedViews: Set<any>
  selectedTag?: RouteLocationNormalizedLoaded
}

export const useTagsViewStore = defineStore("tagsView", {
  state: (): TagsViewState => ({
    visitedViews: [],
    cachedViews: new Set(),
    selectedTag: undefined
  }),
  getters: {
    getVisitedViews(state) {
      return state.visitedViews
    },
    getCachedViews(state): string[] {
      return Array.from(state.cachedViews);
    },
    getSelectedTag(state) {
      return state.selectedTag;
    }
  },
  actions: {
    // 添加标签
    addView(view: any) {
      this.addVisited(view)
      this.newCached()
    },
    addVisited(view: any) {
      const hasVisitedViews = this.visitedViews.some((item) => {
        return item.name === view.name
      })
      if (hasVisitedViews) {
        return
      }
      this.visitedViews.push(Object.assign({}, view, { title: view.meta.title }))
    },

    // 移除标签
    removeView(view: any) {
      this.removeVisited(view)
      this.newCached()
    },

    removeVisited(view: any) {
      const newVisited = this.visitedViews.filter((item) => {
        return item.name !== view.name
      })
      this.visitedViews = newVisited
    },

    // 移除所有标签
    removeAllViews() {
      this.visitedViews = []
      this.cachedViews = new Set()
    },

    // 刷新cachedViews
    newCached() {
      const cachedMap = new Set()
      this.visitedViews.forEach((item) => {
        cachedMap.add(item.name)
      })
      const noChange = Array.from(this.cachedViews).sort().join() === Array.from(cachedMap).sort().join()
      if (noChange) {
        return
      }
      this.cachedViews = cachedMap
    }
  },
})

